#include "CMesh.h"

CMesh::CMesh()
{
	m_pMeshMaterial	= NULL;
	m_pMeshTexture	= NULL;
	m_nNumMtrl		= 0;
}

CMesh::~CMesh()
{
}

bool CMesh::LoadMeshFromFile(LPCSTR pathfile, LPDIRECT3DDEVICE9 d3ddv)
{
	LPD3DXBUFFER			m_pAdjBuffer;
	LPD3DXBUFFER			m_pMtrlBuffer;
	HRESULT	hr;

	hr = D3DXLoadMeshFromX(pathfile,
						   D3DXMESH_MANAGED,
						   d3ddv,
						   &m_pAdjBuffer,
						   &m_pMtrlBuffer,
						   NULL,
						   &m_nNumMtrl,
						   &m_pMesh);

	if (hr != D3D_OK)
	{
		MessageBox(0, "Can not load Mesh", "Error", 0);
		return FALSE;
	}

	if (m_pMtrlBuffer != 0 && m_nNumMtrl != 0)
	{
		D3DXMATERIAL *mtrl = (D3DXMATERIAL*)m_pMtrlBuffer->GetBufferPointer();

		m_pMeshMaterial	= new D3DMATERIAL9[m_nNumMtrl];
		m_pMeshTexture	= new LPDIRECT3DTEXTURE9[m_nNumMtrl];

		if (m_pMeshMaterial == NULL || m_pMeshTexture == NULL)
		{
			MessageBox(0, "Can not malloc", "error", 0);
			return FALSE;
		}
	
		
		for (int i = 0; i < m_nNumMtrl; i++)
		{
			m_pMeshMaterial[i]			= mtrl[i].MatD3D;
			m_pMeshMaterial[i].Ambient	= mtrl[i].MatD3D.Diffuse;
			m_pMeshTexture[i]			= NULL;

			if (mtrl[i].pTextureFilename)
			{
				hr = D3DXCreateTextureFromFile(d3ddv, mtrl[i].pTextureFilename, &m_pMeshTexture[i]);
				
				if (hr != D3D_OK)
				{
					MessageBox(0, "Can not create texture", "error", 0);
					PostQuitMessage(0);
					return FALSE;
				}
			}
		}
	}
	return TRUE;
}

void CMesh::DrawMesh(LPDIRECT3DDEVICE9 d3ddv)
{
	for (int i = 0; i < m_nNumMtrl; i++)
	{
		d3ddv->SetMaterial(&m_pMeshMaterial[i]);
		d3ddv->SetTexture(0, m_pMeshTexture[i]);

		m_pMesh->DrawSubset(i);
	}
}

void CMesh::Release()
{
	if (m_pMesh)
	{
		m_pMesh->Release();
		m_pMesh = NULL;
	}

	if (m_pMeshMaterial)
	{
		delete[] m_pMeshMaterial;
	}

	if (m_pMeshTexture)
	{
		for (int i = 0; i < m_nNumMtrl; i++)
		{
			if (m_pMeshTexture[i])
			{
				m_pMeshTexture[i]->Release();
				m_pMeshTexture[i] = NULL;
			}
		}
		delete[] m_pMeshTexture;
	}
}